package com.atguigu.app.dws.ch;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.Func.MyWindowFunction;
import com.atguigu.bean.TrafficPageViewBean;
import com.atguigu.bean.TrafficPageViewBean_source;
import com.atguigu.util.ClickHouseUtil_hjy;
import com.atguigu.util.DateFormatUtil_hjy;
import com.atguigu.util.MyKafkaUtil_hjy;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.TimestampAssignerSupplier;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.IterativeCondition;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.streaming.api.windowing.windows.Window;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @author hjy
 * @create 2023/3/25 9:07
 */
//数据流:web/app -> 日志服务器(file) -> flume -> Kafka(ODS) -> FlinkApp -> Kafka(DWD) -> FlinkApp -> ClickHouse(DWS)
//程 序:Mock -> file -> f1.sh -> Kafka(ZK) -> BaseLogApp -> Kafka(ZK) -> Dws01TrafficKeywordPageViewWindow -> ClickHouse(ZK)
public class Dws_TrafficVcChArIsNewPageViewWindow_source {
    public static void main(String[] args) throws Exception {
        //todo 1 获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
//        env.enableCheckpointing(5000L, CheckpointingMode.EXACTLY_ONCE);
//        env.getCheckpointConfig().setCheckpointStorage("hdfs://47.102.112.46:8020/gmall-flink/check/baseLogApp");
//        env.getCheckpointConfig().setCheckpointTimeout(60000L);
//        env.setStateBackend(new HashMapStateBackend());
//        System.setProperty("HADOOP_USER_NAME","atguigu");
        //todo 2 从kafka主题（dwd_traffic_page_log）消费数据
        String topic="dwd_traffic_page_log";
        String groupId="dws_traffic_vc_ch_ar_isNew_pageView_window";
        DataStreamSource<String> kafkaDS = env.addSource(MyKafkaUtil_hjy.getKafkaConsumer(topic, groupId));
        //todo 3 将数据转为JSONObj 并过滤 并提取时间戳
        SingleOutputStreamOperator<JSONObject> jsonObjWithWM = kafkaDS.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                JSONObject record = JSON.parseObject(value);
                if (record.getString("page")!=null){
                    out.collect(record);
                }
            }
        })
                .assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                        .withTimestampAssigner(TimestampAssignerSupplier.of(new SerializableTimestampAssigner<JSONObject>() {
                            @Override
                            public long extractTimestamp(JSONObject element, long recordTimestamp) {
                                return element.getLong("ts");
                            }
                        })));
        //todo 4 按照mid分组
        KeyedStream<JSONObject, String> keyedStream = jsonObjWithWM.keyBy(value -> value.getJSONObject("common").getString("mid"));

        //todo 5 转为javaBean对象
        SingleOutputStreamOperator<TrafficPageViewBean_source> javaBeanDS = keyedStream.map(new RichMapFunction<JSONObject, TrafficPageViewBean_source>() {
            private ValueState<String> lastDtState;

            @Override
            public void open(Configuration parameters) throws Exception {
                StateTtlConfig ttlCfg = StateTtlConfig.newBuilder(Time.days(1))
                        .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
                        .build();
                ValueStateDescriptor<String> valueStateDescriptor = new ValueStateDescriptor<>("last_dt", String.class);
                valueStateDescriptor.enableTimeToLive(ttlCfg);
                lastDtState = getRuntimeContext().getState(valueStateDescriptor);
            }

            @Override
            public TrafficPageViewBean_source map(JSONObject value) throws Exception {
                String lastDt = lastDtState.value();
                String curtDt = DateFormatUtil_hjy.toDate(value.getLong("ts"));
                JSONObject common = value.getJSONObject("common");
                JSONObject page = value.getJSONObject("page");
                String vc = common.getString("vc");
                String ch = common.getString("ch");
                String ar = common.getString("ar");
                String isNew = common.getString("is_new");
                String lastPageId = page.getString("last_page_id");
                Long uv = 0L;
                Long sv = 0L;

                if (lastDt == null || !lastDt.equals(curtDt)) {
                    lastDtState.update(curtDt);
                    uv = 1L;
                }
                if (lastPageId == null) {
                    sv = 1L;
                }
//                return new TrafficPageViewBean("",
//                        "",
//                        vc,
//                        ch,
//                        ar,
//                        isNew,
//                        uv,
//                        sv,
//                        1L,
//                        page.getLong("during_time"),
//                        null);
                return TrafficPageViewBean_source.builder()
                        .vc(vc)
                        .ch(ch)
                        .ar(ar)
                        .isNew(isNew)
                        .uvCt(uv)
                        .svCt(sv)
                        .pvCt(1L)
                        .durSum(page.getLong("during_time"))
                        .build();
            }
        });

        //todo 7 按照来源分组
        KeyedStream<TrafficPageViewBean_source, String> keyedByChDS = javaBeanDS.keyBy(TrafficPageViewBean_source::getCh);
        //todo 8 开窗聚合
        SingleOutputStreamOperator<TrafficPageViewBean_source> reduceDS = keyedByChDS.window(TumblingEventTimeWindows.of(org.apache.flink.streaming.api.windowing.time.Time.seconds(10)))
                .reduce(new ReduceFunction<TrafficPageViewBean_source>() {
                    @Override
                    public TrafficPageViewBean_source reduce(TrafficPageViewBean_source value1, TrafficPageViewBean_source value2) throws Exception {
                        value1.setUvCt(value1.getUvCt() + value2.getUvCt());
                        value1.setPvCt(value1.getPvCt() + value2.getPvCt());
                        value1.setSvCt(value1.getSvCt() + value2.getSvCt());
                        value1.setDurSum(value1.getDurSum() + value2.getDurSum());
                        return value1;
                    }
                }, new WindowFunction<TrafficPageViewBean_source, TrafficPageViewBean_source, String, TimeWindow>() {
                    @Override
                    public void apply(String s, TimeWindow window, Iterable<TrafficPageViewBean_source> input, Collector<TrafficPageViewBean_source> out) throws Exception {
                        TrafficPageViewBean_source next = input.iterator().next();
                        out.collect(MyWindowFunction.getWindow(next,window));
                    }
                });

        //todo 7 输出数据到clickHouse
        reduceDS.print("reduceDS");
        reduceDS.addSink(ClickHouseUtil_hjy.getClickHouseSink("insert into dws_traffic_ch_page_view_window values(?,?,?,?,?,?,?,?,?,?,?)"));
        //todo 8 启动任务
        env.execute();

    }
}
